package com.tie.jun.ge.xxljob.app;

import com.tie.jun.ge.xxljob.domain.TaskManagerDO;
import com.tie.jun.ge.xxljob.extenal.XxlExternalApl;
import com.tie.jun.ge.xxljob.extenal.entity.XxlJobInfo;
import com.tie.jun.ge.xxljob.service.TaskManagerService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @program: springboot
 * @description: 任务管理app层
 * @author: getiejun
 * @create: 2025-10-27 23:15
 **/
@Component
public class TaskManagerApp {

    @Resource
    private XxlExternalApl xxlExternalApl;

    @Resource
    private TaskManagerService taskManagerService;

    /**
     * 新增任务
     */
    public void add(TaskManagerDO taskManagerDO) {
        //1.发送请求  2.记录数据库
        XxlJobInfo xxlJobInfo = getCommonXxlJobInfo();
        xxlJobInfo.setJobDesc(taskManagerDO.getTaskDesc());
        xxlJobInfo.setScheduleType(taskManagerDO.getScheduleType()); // CRON
        xxlJobInfo.setScheduleConf(taskManagerDO.getScheduleConf()); // 0/2 * * * * ?
        xxlJobInfo.setExecutorHandler(taskManagerDO.getExecutorHandler());// demoJobHandler

        String jobId = xxlExternalApl.add(xxlJobInfo);
        taskManagerDO.setJobId(jobId);

        taskManagerService.save(taskManagerDO);
    }

    private XxlJobInfo getCommonXxlJobInfo() {
        XxlJobInfo xxlJobInfo = new XxlJobInfo();
        xxlJobInfo.setJobGroup(1);
        xxlJobInfo.setAuthor("XXL");
        xxlJobInfo.setGlueType("BEAN");
        xxlJobInfo.setExecutorRouteStrategy("FIRST");
        xxlJobInfo.setMisfireStrategy("DO_NOTHING");
        xxlJobInfo.setExecutorBlockStrategy("SERIAL_EXECUTION");
        return xxlJobInfo;
    }

    public List<TaskManagerDO> listAll() {
        return taskManagerService.listAll();
    }

    public void trigger(TaskManagerDO taskManagerDO) {
        XxlJobInfo xxlJobInfo = new XxlJobInfo();
        xxlJobInfo.setId(Integer.parseInt(taskManagerDO.getJobId()));
        xxlExternalApl.trigger(xxlJobInfo);
    }
}
